<?php 
/****

	If you want the best of the world,
give the world your best anytime！
            				——不二
                							
****/

defined('ACCESS')||exit('Forbidden!');

//文章相关控制器
class ArticleAction extends Action {
	protected $art;
	protected $cat;

	public function __construct(){
		parent::__construct();

		$this->art = new ArticleModel();
		$this->cat = new CategoryModel();
	}

	//添加文章
	public function add(){
		if(empty($_POST)){
			$data = $this->cat->select();
			//显示出所有的栏目id
			$this->assign('data',$data);
			$this->display('art_add.html');
		}else{
			//print_r($_POST);
			$res = $this->art->insert($_POST);
			if($res){
				//该栏目下的文章数+1
				$data = $this->cat->find($_POST['cat_id']);
				$data['num'] +=1;
				$this->cat->update($data);
				$this->success('文章添加成功','index.php?group=Admin&module=Article&action=lists');
			}else {
				$this->failue('文章添加失败','index.php?group=Admin&module=Article&action=add');
			}
		}
	}

	public function lists(){
		$data = $this->art->select();
		$this->assign('data',$data);
		$this->display('art_list.html');
	}

	public function del(){
		$id = $this->I('id');
		$data = $this->art->find($id);
		if(!$data){
			$this->failure('文章不存在','index.php?group=Admin&module=Article&action=lists');
		}
		$res = $this->art->delete($id);
		if(!$res){
			$this->failure('删除失败','index.php?group=Admin&module=Article&action=lists');
		}else {
			//该栏目下的文章数-1
			$data = $this->cat->find($data['cat_id']);
			$data['num'] -=1;
			$this->cat->update($data);
			//删除该文章下的所有评论
			$com = new CommentModel();
			$com->deleteAll("art_id = $id");
			
			header('Location:index.php?group=Admin&module=Article&action=lists');
		}
	}

	public function edit(){
		$id = $this->I('id');
		$data = $this->art->find($id);
		if(!$data){
			$this->failue('文章不存在','index.php?group=Admin&module=Article&action=lists');
		}
		if(empty($_POST)){
			//
			$cat_data = $this->cat->select();
			//显示出所有的栏目id
			$this->assign('cat',$cat_data);
			//取出默认值
			$this->assign('data',$data);
			$this->display('art_edit.html');
		}else {
			$_POST['art_id'] = $id;
			$res = $this->art->update($_POST);
			if(!$res){
				$this->failue('修改失败','index.php?group=Admin&module=Article&action=lists');
			}else {
				$this->success('修改成功','index.php?group=Admin&module=Article&action=lists');
			}
		}
	}
}

